<?php

namespace Shop\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Shop\AdminBundle\Controller\BaseController;

/**
 * Class LoginController
 * @package Shop\AdminBundle\Controller
 * @Route("/admin")
 */
class LoginController extends BaseController
{
    /**
     * @Route("/login", name="admin_login")
     * @Method("GET")
     * @Template("ShopAdminBundle:Login:login.html.twig")
     */
    public function loginAction(){
        return [
            'pg_login'=>true
        ];
    }

    /**
     * @Route("/handle_login", name="admin_login_handle")
     * @Method("POST")
     */
    public function handleLoginAction(Request $request){

        if($request->isXmlHttpRequest()){
            $username=$request->request->get('username');
            $password=$request->request->get('password');

            $em = $this->getDoctrine()->getManager();
            $userRepo=$this->getRepo('adminUser');

            $user=$userRepo->findOneBy(['username'=>$username]);

            if(!empty($user)){
                $salt=$user->getSalt();
                $pass=$user->getPassword();

                if($pass === md5($salt. $password)){
                    $sess=$this->get('session');

                    $userSession=[
                      'name'=>  $user->getUsername(),
                      'password'=> $user->getPassword(),
                      'lastlogin'=> $user->getLastLogin()
                    ];

                    $sess->set('user', $userSession);
                }

                //update entity
                $user->setCountLogin($user->getCountLogin()+1);
                $user->setLastLogin(time());

                $em->persist($user);
                $em->flush();
                $this->setAjaxMsg('success',true);
            }

        }
        return $this->jsonResponse();

    }

    /**
     * @Route("/logout")
     * @Method("GET")
     */
    public function logoutAction(Request $request){
        if($request->isXmlHttpRequest()){
            $sess=$this->get('session');
            $sess->remove('user');

            $this->setAjaxMsg('success',true);
        }

        return $this->jsonResponse();
    }

    /**
     * admin user register
     * @Route("/register", name="admin_register")
     * @Method("GET")
     * @Template("ShopAdminBundle:Login:register.html.twig")
     */
    public function registerAction(){
        return [
            'pg_login'=>true,
        ];
    }

}
